import { message, Steps, Button, Form, Cascader, Input, Select } from "antd";
import React, { useState, useEffect } from "react";
import styles from "./style.less";
import { connect, history } from "umi";
import {
  mobileReg,
  mobileRegMessage,
  passWordReg,
  passWordRegMessage,
} from "@/utils/regExp";
import Https2 from "@/utils/Https2";
import Https from "@/utils/Https";
import { getItem } from "@/utils/localstorage";
import { PROJECT_NAME, TOKEN } from "@/constants";
import logoPng from "@/assets/imgs/logo.png";
import { UserOutlined } from "@ant-design/icons";
const RegisterPage = (props) => {
  if (getItem(TOKEN)) {
    history.replace("/welcome");
  }
  const [current, setCurrent] = useState(0);
  const { dispatch, arrRegion, businessTypeArr, customer } = props;
  const [form] = Form.useForm();
  const [codeObj, setCodeObj] = useState({});
  const [newPhone, setNewPhone] = useState("");
  const [code, setCode] = useState("");
  //验证码
  const [smsCode, setSmsCode] = useState("");
  const [btnStatus, setBtnStatus] = useState(false);
  const [count, setCount] = useState(60);
  const [oneParams, setOneParams] = useState({});
  useEffect(() => {
    dispatch({
      type: "userRegister/pageInit",
    });
  }, []);

  //基本信息保存
  const queryRegister = async () => {
    let res = await form.validateFields();
    console.log(res, "_res");
    if (res.password != res.repeatPassword) {
      message.error("确认密码与密码不一致");
      return;
    }
    let params = { ...res, smsCode };
    let result: any = await Https.post("/auth/tenant/checkInfo", params, true);
    if (result.code == 200) {
      setOneParams(params);
      setCurrent(1);
    } else {
      message.error(result.msg);
    }
  };
  //注册
  const saveRegister = async () => {
    let res = await form.validateFields();
    console.log(res, "_res");
    let params = { ...res, ...oneParams };
    params.region = params.region.join("-");
    console.log(params, "-params");
    dispatch({
      type: "userRegister/queryRegister",
      params,
      callback: () => {
        setCurrent(2);
      },
    });
  };
  const getImg = async () => {
    const res = await Https2.get("/auth/code", {}, true);
    if (res.code == 200) {
      setCodeObj(res.data);
    }
  };
  //获取验证码
  const sendSms = async () => {
    const result = await Https.post(
      "/auth/preRegister",
      { phoneNumber: newPhone, uuid: codeObj.uuid, code: code },
      true
    );
    if (result.code === 200) {
      message.success("已发送验证码");
      setBtnStatus(true);
      let newCount = count;
      let timer = setInterval(() => {
        if (newCount > 0) {
          setCount(newCount--);
        } else {
          setCount(60);
          setBtnStatus(false);
          clearInterval(timer);
        }
      }, 1000);
    } else {
      message.error(result.msg || "发送失败，请稍后再试！");
    }
  };
  useEffect(() => {
    getImg();
  }, []);
  return (
    <div className={styles.FindBox}>
      <div className={styles.lefgBg}>
        <div className={styles.leftHeader}>
          <img src={logoPng} alt="" />
          <span>{PROJECT_NAME}</span>
        </div>
        <div className={styles.leftSteps}>
          <Steps
            direction="vertical"
            current={current}
            items={[
              {
                title: "基本信息",
              },
              {
                title: "品牌信息",
              },
              {
                title: "完成",
              },
            ]}
          />
        </div>
      </div>
      <div style={{ padding: "0 80px", width: "100%" }}>
        <div className={styles.content}>
          <div className={styles.loginTitle}>
            注册账号<span>(Register)</span>
          </div>
          <div className={styles.loginTitleTips}>
            {current == 0 ? "基础信息" : current == 1 ? "品牌信息" : "完成"}
          </div>
          {(current == 0 || current == 1) && (
            <Form
              form={form}
              className={styles.form}
              labelCol={{ span: 0 }}
              wrapperCol={{ span: 24 }}
            >
              {current == 0 && (
                <>
                  <Form.Item label="手机号码" name="username">
                    <Input
                      prefix={<UserOutlined />}
                      placeholder="请输入登录账号，不能修改（不写则默认为手机号）"
                    />
                  </Form.Item>
                  <Form.Item
                    label="手机号码"
                    name="contactPhone"
                    rules={[
                      {
                        required: true,
                        message: "请输入手机号！",
                      },
                      { pattern: mobileReg, message: mobileRegMessage },
                    ]}
                  >
                    <Input
                      prefix={<UserOutlined />}
                      placeholder="请输入手机号"
                      onChange={(e) => {
                        setNewPhone(e.target.value);
                      }}
                      maxLength={11}
                    />
                  </Form.Item>
                  <Form.Item
                    className={styles.codeWrapper}
                    label="图形验证码"
                    required={true}
                  >
                    <Form.Item
                      name="code"
                      noStyle
                      rules={[
                        {
                          required: true,
                          message: "请输入图形验证码！",
                        },
                      ]}
                    >
                      <Input
                        maxLength={4}
                        onChange={(e) => {
                          setCode(e.target.value);
                        }}
                        placeholder="请输入图形验证码"
                      />
                    </Form.Item>
                    <img
                      onClick={() => getImg()}
                      className={styles.codePic}
                      src={
                        codeObj.img
                          ? `data:image/png;base64,${codeObj?.img}`
                          : {}
                      }
                    />
                  </Form.Item>
                  <Form.Item
                    label="验证码"
                    className={styles.smsCodeBox}
                    required={true}
                  >
                    <Form.Item
                      name="smsCode"
                      rules={[
                        {
                          required: true,
                          message: "请输入短信验证码！",
                        },
                      ]}
                      noStyle
                    >
                      <Input
                        placeholder="请输入短信验证码"
                        maxLength={4}
                        onChange={(e) => {
                          setSmsCode(e.target.value);
                        }}
                      />
                    </Form.Item>
                    <Button
                      style={{
                        marginLeft: "10px",
                        height: "40px",
                        width: "130px",
                      }}
                      disabled={
                        newPhone.length != 11 || code.length != 4 || btnStatus
                      }
                      onClick={() => {
                        sendSms();
                      }}
                    >
                      {!btnStatus ? "获取短信验证码" : count + "s"}
                    </Button>
                  </Form.Item>
                  <Form.Item
                    label="登录密码"
                    name="password"
                    rules={[
                      { required: true, message: "登录密码不能为空" },
                      { pattern: passWordReg, message: passWordRegMessage },
                    ]}
                  >
                    <Input.Password placeholder="请输入登录密码,6-12位包含数字、字母英文符号" />
                  </Form.Item>
                  <Form.Item
                    label="确认密码"
                    name="repeatPassword"
                    rules={[
                      { required: true, message: "确认密码不能为空" },
                      { pattern: passWordReg, message: passWordRegMessage },
                    ]}
                  >
                    <Input.Password placeholder="重复密码,6-12位包含数字、字母英文符号" />
                  </Form.Item>
                  <Form.Item label="推荐码" name="joinCode">
                    <Input placeholder="请输入推荐码，没有则可不填" />
                  </Form.Item>
                  <div className={styles.btn_wrapper}>
                    <Button
                      className={styles.btn}
                      type="primary"
                      onClick={() => {
                        queryRegister();
                      }}
                    >
                      下一步
                    </Button>
                  </div>
                  <div className={styles.btn_link}>
                    <a
                      onClick={() => {
                        history.push("/user/login");
                      }}
                    >
                      返回登录{">>"}
                    </a>
                  </div>
                </>
              )}
              {current == 1 && (
                <>
                  <Form.Item
                    label="品牌名称"
                    name="brandName"
                    rules={[{ required: true, message: "请输入品牌名称!" }]}
                  >
                    <Input
                      prefix={<UserOutlined />}
                      placeholder="请输入品牌名称，限20个字，默认作为总店名称"
                      maxLength={20}
                    />
                  </Form.Item>
                  <Form.Item
                    label="业务类型"
                    name="businessType"
                    rules={[{ required: true, message: "请选择业务类型!" }]}
                  >
                    <Select
                      options={businessTypeArr}
                      fieldNames={{
                        label: "dictLabel",
                        value: "dictValue",
                      }}
                      placeholder="请选择业务类型"
                    />
                  </Form.Item>
                  <Form.Item
                    label="所属区域"
                    name="region"
                    rules={[{ required: true, message: "请选择所属区域!" }]}
                  >
                    <Cascader
                      options={arrRegion}
                      fieldNames={{
                        label: "label",
                        value: "label",
                      }}
                      placeholder="请选择所属区域"
                    />
                  </Form.Item>
                  <div className={styles.btn_wrapper}>
                    <Button
                      className={styles.btn}
                      type="primary"
                      onClick={() => {
                        saveRegister();
                      }}
                    >
                      注册
                    </Button>
                  </div>
                  <div className={styles.btn_link}>
                    <a
                      onClick={() => {
                        history.push("/user/login");
                      }}
                    >
                      返回登录{">>"}
                    </a>
                  </div>
                </>
              )}
            </Form>
          )}
          {current == 2 && (
            <div className={styles.successBox}>
              <div className={styles.titleTip}>
                <img src={require("./check.png")} />
                <div>
                  <div className={styles.titleText}>
                    恭喜,已成功注册,您可以返回登录
                  </div>
                  <span>添加专属客服，获得贴心一对一咨询服务</span>
                </div>
              </div>
              <div className={styles.contact}>
                <img
                  src="https://oss.zkwcloud.com/imgs/imgs/Sam.png"
                  style={{ width: "180px" }}
                  alt=""
                />
                {customer && customer.length > 0 && (
                  <div className={styles.tel}>
                    <p>姓名：{customer[0].value}</p>
                    <p>职位：{customer[1].value}</p>
                    <p>手机号码：{customer[2].value}</p>
                  </div>
                )}
              </div>
              <div className={styles.btn_login}>
                <Button
                  className={styles.btn}
                  type="primary"
                  onClick={() => history.push("/user/login")}
                >
                  立即登录
                </Button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ userRegister }) => ({
  ...userRegister,
}))(RegisterPage);
